import 'dart:io';

import 'package:flutter/material.dart';

import 'package:webview_cookie_manager/webview_cookie_manager.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const WebViewPage(),
    );
  }
}

class WebViewPage extends StatefulWidget {
  const WebViewPage({Key? key}) : super(key: key);

  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  final cookieManager = WebviewCookieManager();
  WebViewController controller = WebViewController();

  // final String _url = 'https://developer.huawei.com/consumer/cn/doc/search?type=all&val=BusinessError';
  final String _url = 'https://www.nvidia.cn';
  final String cookieValue = 'some-cookie-value';
  final String domain = 'm.youtube.com';
  final String cookieName = 'some_cookie_name';

  @override
  void initState() {
    super.initState();
    cookieManager.clearCookies();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..loadRequest(Uri.parse(_url))
      ..setNavigationDelegate(NavigationDelegate(
        onPageFinished: (_) async {
          final gotCookies = await cookieManager.getCookies(_url);
          for (var item in gotCookies) {
            print('mlzh，${item}');
          }
        },
      ));
    cookieManager.setCookies([
      Cookie(cookieName, cookieValue)
        ..domain = domain
        ..expires = DateTime.now().add(Duration(days: 10))
        ..httpOnly = false
    ]);
  }

  void setCookiesFunc() {
    Cookie cookie = new Cookie('cookieName', 'cookieValue');
    cookie.secure = true;
    cookie.httpOnly = true;
    cookie.expires = DateTime.now().add(Duration(days: 10));
    List<Cookie> cookieList = [cookie];
    cookieManager.setCookies(cookieList, origin: 'https://www.nvidia.cn');
  }

  void clearCookies() {
    cookieManager.clearCookies();
    // 出现弹窗提示 清理cookies成功
    _showInfoDialog('提示', "Cookies清理成功");
  }

  void hasCookie() async {
    bool cookiesExist = await cookieManager.hasCookies();
    String content = cookiesExist ? '存在cookie' : '不存在cookie';
    _showInfoDialog('提示', content);
  }

  // 弹窗提示
  void _showInfoDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            child: const Text('确定'),
            onPressed: () => Navigator.of(context).pop(context),
          )
        ],
      ),
    );
  }

  void removeCookie() {
    cookieManager.removeCookie(_url);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
          actions: [
            IconButton(
              icon: Icon(Icons.ac_unit),
              onPressed: () async {
                // TEST CODE
                List<Cookie> cookieList = await cookieManager.getCookies(_url);
                print("mlzh，cookieList length: ${cookieList.length}");
                for (Cookie ck in cookieList) {
                  print('mlzh，${ck.toString()}');
                }
              },
            ),
            IconButton(icon: Icon(Icons.add), onPressed: setCookiesFunc),
            IconButton(icon: Icon(Icons.delete), onPressed: clearCookies),
            IconButton(icon: Icon(Icons.device_unknown), onPressed: hasCookie),
            IconButton(icon: Icon(Icons.beach_access), onPressed: removeCookie)
          ],
        ),
        body: WebViewWidget(controller: controller),
      ),
    );
  }
}
